const Router = require("koa-router")
const { Op } = require("sequelize")
const ResBody = require("../struct/ResBody")
const { Dict, DictDetail, User } = require("../model")
const router = new Router()
const utils = require("../utils/index.js")
const { SystemController } = require("../controller")

// 获取字典列表
router.get("/dict", async ctx => {
  const list = await Dict.findAll()
  ctx.body = new ResBody({ data: { list } })
})
// 字典详情
router.get("/dictDetail", async ctx => {
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return (ctx.body = new ResBody({
      success: false,
      code: 403,
      msg: "拒绝访问API"
    }))
  }
  const { dict_id, name } = ctx.query
  if (dict_id) {
    const list = await DictDetail.findAll({
      where: { dict_id }
    })
    ctx.body = new ResBody({ data: { list } })
  }
  // TODO dict、dictDetail 联表查询
  else if (name) {
    const list = await DictDetail.findAll({
      where: { name }
    })
    ctx.body = new ResBody({ data: { list } })
  } else {
    ctx.body = new ResBody({ data: null, code: 500, msg: "参数不全" })
  }
})
// 获取所有字典
router.get("/allDict", async ctx => {
  const { role } = ctx.state.user
  console.log('allDict==', role);
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return (ctx.body = new ResBody({
      success: false,
      code: 403,
      msg: "拒绝访问API"
    }))
  }
  const store_id = ctx.header.storeid
  const { dict_id, name } = ctx.query
  const result = await SystemController.getAllDict(store_id)
  ctx.body = new ResBody({ data: result })
})
// 批量获取字典详细数据
router.get("/batchDictDetails", async ctx => {
  const { role } = ctx.state.user
  console.log('batchDictDetails==', role);
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return (ctx.body = new ResBody({
      success: false,
      code: 403,
      msg: "拒绝访问API"
    }))
  }
  const store_id = ctx.header.storeid
  const { dict_id, names } = ctx.query;
  console.log(
    "batchDictDetails--%s--%s==",
    JSON.stringify(ctx.request.body),
    JSON.stringify(ctx)
  )
  console.log('batchDictDetails--names==', names);
  const result = await SystemController.getBatchDictDetails(store_id, names)
  ctx.body = new ResBody({ data: result })
})
// 添加字典；
router.post("/dictAdd", async ctx => {
  console.log(
    "add--%s--%s==",
    JSON.stringify(ctx.request.body),
    JSON.stringify(ctx.state.user)
  )
  const { role } = ctx.state.user
  const store_id = ctx.header.storeid
  console.log("dictAdd--store_id==%s==", store_id)

  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return (ctx.body = new ResBody({
      success: false,
      code: 403,
      msg: "拒绝访问API"
    }))
  }
  const { name, remark } = ctx.request.body
  utils.checkParams({ name, remark })

  const res = await Dict.findOrCreate({
    where: {
      store_id,
      [Op.or]: [{ name }, { remark }]
    },
    defaults: { store_id, name, remark }
  })
  console.log("findGoods--%s==", res)
  ctx.body = new ResBody({ data: res })
})

// 添加字典；
router.post("/dictDetailEdit", async ctx => {
  console.log(
    "add--%s--%s==",
    JSON.stringify(ctx.request.body),
    JSON.stringify(ctx.state.user)
  )
  const { role } = ctx.state.user
  const store_id = ctx.header.storeid

  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return (ctx.body = new ResBody({
      success: false,
      code: 403,
      msg: "拒绝访问API"
    }))
  }
  const { id, label, value, sort, dict_id } = ctx.request.body
  utils.checkParams({ label, value, sort, dict_id })

  console.log("DictDetail--res--%s==", id)
  if (id) {
    const findList = await DictDetail.findAll({
      where: {
        dict_id,
        [Op.or]: [{ id }, { label }, { value }]
      }
    })
    console.log("DictDetail--findList--%s==", JSON.stringify(findList))
    if (findList.length === 0) {
      return (ctx.body = new ResBody({
        data: null,
        code: 500,
        msg: `抱歉。未找到这个条数据 ${id}`
      }))
    } else if (findList.length > 1) {
      let isLabel = findList.find(d => d.label === label && d.id !== id)
      let isValue = findList.find(d => d.value === value && d.id !== id)
      let msg = ""
      if (isLabel) {
        msg = `字典标签 ${label} 已存在`
        if (isValue) {
          msg = `字典标签 ${label} 字典值 ${value} 已存在`
        }
      } else if (isValue) {
        msg = `字典值 ${value} 已存在`
      }
      return (ctx.body = new ResBody({ code: 500, msg }))
    } else if (findList.length === 1 && findList[0].id !== id) {
      return (ctx.body = new ResBody({
        data: null,
        code: 500,
        msg: `抱歉。未找到这个条数据 ${id}`
      }))
    }
    ctx.body = new ResBody({ data: "false" })
    const res = await DictDetail.update(
      { label, value, sort },
      { where: { id } }
    )
    ctx.body = new ResBody({ data: res })
  } else {
    const res = await DictDetail.findOrCreate({
      where: {
        dict_id,
        [Op.or]: [{ label }, { value }]
      },
      // where: { name, remark },
      defaults: { label, value, sort, dict_id }
    })
    console.log("findGoods--%s==", res)
    ctx.body = new ResBody({ data: res })
  }
})

module.exports = router.routes()
